module.exports = {
  /**
   * 菜单管理模块
   * 权限标识：
   *  - READ_MENU
   *  - ADD_MENU
   *  - DELETE_MENU
   *  - UPDATE_MENU
   */

  /**
   * 获取当前用户对应角色的菜单
   */
  async getAuthMenuList() {
    const { body = {} } = this.getHttpInfo()
    const { clientInfo } = JSON.parse(body)
    const authInfo = this.authInfo || {}
    const DB = uniCloud.databaseForJQL({ clientInfo })

    // 查用户
    let user = await DB.collection('uni-id-users')
      .where({ _id: authInfo.uid })
      .field('_id,role')
      .get({ getOne: true })

    // 查角色
    const roles = await DB.collection('uni-id-roles')
      .where(`role_id in ${JSON.stringify(user.data.role || [])}`)
      .get()
    roles.data = roles.data ?? [{}]

    // 菜单id列表（去重）
    let menuIds = JSON.stringify([
      ...new Set(
        roles.data.reduce((ov, nv) => [...ov, ...nv.half_menus, ...nv.menus], [])
      )
    ])

    // 查菜单
    const menus = await DB.collection('mo-menu')
      .where(`type != 2 && _id in ${menuIds}`)
      .orderBy('order_num', 'asc')
      .get({ getTree: {} })

    return menus
  },

  /**
   * 获取全部菜单
   */
  async getMenuTree() {
    const { body = {} } = this.getHttpInfo()
    const { clientInfo } = JSON.parse(body)

    const MoMenu = uniCloud.databaseForJQL({ clientInfo }).collection('mo-menu')
    let res = await MoMenu.orderBy('order_num', 'asc').get({
      getTree: {}
    })

    return res
  },

  /**
   * 获取上级菜单
   */
  async getMenuTreeParent() {
    const { body = {} } = this.getHttpInfo()
    const { clientInfo } = JSON.parse(body)

    const MoMenu = uniCloud.databaseForJQL({ clientInfo }).collection('mo-menu')
    const res = await MoMenu.orderBy('order_num', 'asc')
      .field('_id,title,parent_id,parent_title,type')
      .get({
        getTree: {}
      })

    return res
  },

  /**
   * 新增菜单
   */
  async addMenu() {
    const { body = {} } = this.getHttpInfo()
    const { params, clientInfo } = JSON.parse(body)

    //剔除报错字段
    delete params._id
    const MoMenu = uniCloud.databaseForJQL({ clientInfo }).collection('mo-menu')
    const res = await MoMenu.add(params)

    return res
  },

  /**
   * 更新菜单
   */
  async updateMenu() {
    const { body = {} } = this.getHttpInfo()
    const { params, clientInfo } = JSON.parse(body)
    let _id = params._id

    //剔除报错字段
    delete params._id
    delete params.children

    const MoMenu = uniCloud.databaseForJQL({ clientInfo }).collection('mo-menu')
    const res = await MoMenu.where({ _id }).update(params)

    return res
  },

  /**
   * 删除菜单
   */
  async deleteMenu() {
    const { body = {} } = this.getHttpInfo()
    const { params, clientInfo } = JSON.parse(body)

    const MoMenu = uniCloud.databaseForJQL({ clientInfo }).collection('mo-menu')
    const res = await MoMenu.where({ _id: params._id }).remove()

    return res
  }
}
